package run;

import processing.core.PApplet;
import processing.core.PImage;
import processing.core.PVector;

public class CVMarioGameEnv {

	int w, h;
	PApplet parent;
	int[] pix;
	
	public CVMarioGameEnv(PImage pImage, PApplet applet) {

		pImage.filter(applet.THRESHOLD, 0.5F);
		pImage.loadPixels();
		pix = pImage.pixels;
		
		w = pImage.width;
		h = pImage.height;
		
		parent = applet;
	}
	
	// scan the range... return true or false
	public boolean collidesWithObj(PVector a) {
		if (! outOfBounds(a))
			return pixelOccupied(a);
		else return false;
	}
	
	public boolean pixelOccupied(PVector pt) {
		if (outOfBounds(pt))
			return false;
			
		if ( getPixel(pt) == parent.color(0,0,0) )
			return true;
		else return false;
	}
	
	public int getPixel(PVector v) {
		return pix[ (int)  ((w * v.y) + v.x) ];
	}

	// scan the range... return the length of the range
	public PVector min_intersection(PVector a, PVector b) {
		PVector diff = PVector.sub(b, a);
		
		int steps = (int) diff.mag();
		PVector step = PVector.div(diff, diff.mag());
		
		for (int i = 0; i <= steps; i++) {
			PVector pixelLoc = PVector.add(a, PVector.mult(step, i));
			if (pixelOccupied( pixelLoc)) {
				return PVector.mult(diff, i);
			}
		}
		
		return diff;
	}

	public boolean outOfBounds(PVector p) {
		return (p.x < 0 || p.x > w || p.y < 0 || p.y > h);
	}

}
